<template>
  <div id="layout_app">
    <div class="layout-header">
      <div class="logo">QIANKUN-EXAMPLE</div>
      <ul class="sub-apps">
        <li v-for="item in microApps" :class="{active: item.activeRule === current}" :key="item.name" @click="goto(item)">
          {{ item.name }}
        </li>
      </ul>
    </div>
    <div id="subapp_viewport"></div>
  </div>
</template>

<script>
import microApps from './micro-app'
export default {
  name: 'App',
  data() {
    return {
      microApps,
      current: "/vue1/"
    }
  },
  created () {
    this.bindCurrent();
  },
  mounted () {
    this.listenRouterChange()
  },
  methods: {
    bindCurrent () {
      const path = window.location.pathname
      if (this.microApps.findIndex(item => item.activeRule === path) >= 0) {
        this.current = path
      }
    },
    goto (item) {
      history.pushState(null, item.activeRule, item.activeRule);
    },
    listenRouterChange () {
      const _wr = function (type) {
        const orig = history[type]
        return function () {
          const rv = orig.apply(this, arguments)
          const e = new Event(type)
          e.arguments = arguments
          window.dispatchEvent(e)
          return rv
        }
      }
      history.pushState = _wr('pushState')

      window.addEventListener('pushState', this.bindCurrent)
      window.addEventListener('popstate', this.bindCurrent)

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('pushState', this.bindCurrent)
        window.removeEventListener('popstate', this.bindCurrent)
      })
    }
  }
}
</script>
<style>
.my_font {
    color: rebeccapurple;
  }
</style>
<style scoped lang="less">
#layout_app {
  margin: 0;
  text-align: center;
  color: #333;
  font-family: "微软雅黑";
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.layout-header{
    height: 50px;
    width: 100%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    line-height: 50px;
    position: relative;
    .logo {
      float: left;
      margin: 0 50px;
    }
    .sub-apps {
      list-style: none;
      margin: 0;
      li{
        list-style: none;
        display: inline-block;
        padding: 0 20px;
        cursor: pointer;
        &.active{
          color: #42b983;
          text-decoration: underline;
        }
      }
    }
  }
</style>
